//token设置
package com.cuijian.demo.util;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class TokenManager {

    private static final Map<String, TokenInfo> tokenMap = new ConcurrentHashMap<>();

    // Token有效期：7天
    private static final long TOKEN_EXPIRE_TIME = 7 * 24 * 60 * 60 * 1000;

    public static class TokenInfo {
        private Long userId;
        private String username;
        private long createTime;

        public TokenInfo(Long userId, String username) {
            this.userId = userId;
            this.username = username;
            this.createTime = System.currentTimeMillis();
        }

        // getter methods
        public Long getUserId() { return userId; }
        public String getUsername() { return username; }
        public long getCreateTime() { return createTime; }

        public boolean isExpired() {
            return System.currentTimeMillis() - createTime > TOKEN_EXPIRE_TIME;
        }
    }

    /**
     * 创建token
     */
    public static String createToken(Long userId, String username) {
        String token = PasswordUtil.generateToken();
        tokenMap.put(token, new TokenInfo(userId, username));
        return token;
    }

    /**
     * 验证token
     */
    public static boolean verifyToken(String token) {
        if (token == null || token.isEmpty()) {
            return false;
        }

        TokenInfo tokenInfo = tokenMap.get(token);
        if (tokenInfo == null || tokenInfo.isExpired()) {
            tokenMap.remove(token); // 清理过期token
            return false;
        }

        return true;
    }

    /**
     * 获取token信息
     */
    public static TokenInfo getTokenInfo(String token) {
        return tokenMap.get(token);
    }

    /**
     * 删除token
     */
    public static void removeToken(String token) {
        tokenMap.remove(token);
    }

    /**
     * 清理过期token
     */
    public static void cleanExpiredTokens() {
        tokenMap.entrySet().removeIf(entry -> entry.getValue().isExpired());
    }
}